<template>
  <div class="container">
    <h3>vue+openlayers: 绘制闪光点划线</h3>
    <div id="vue-openlayers" ref="map" class="map-x"></div>
  </div>
</template>

<script>
import 'ol/ol.css';
import { Map,View} from 'ol'
import Tile from 'ol/layer/Tile'
import XYZ from "ol/source/XYZ";
import VectorLayer from 'ol/layer/Vector'; // 矢量图层
import VectorSource from 'ol/source/Vector'; // 矢量数据源
import Draw from 'ol/interaction/Draw'; // 绘制
import { Fill, Stroke, Style, Icon } from 'ol/style';
import Feature from 'ol/Feature'; // 要素
import { Point, LineString, Polygon, Circle } from 'ol/geom'; // 点要素
import CircleStyle from 'ol/style/Circle';
import { fromLonLat, toLonLat, transform } from 'ol/proj';
export default {
  data() {
    return {
      map: null,
      lineSource: new VectorSource({ wrapX: false }),
      status: false,
      VectorLayer: null,
      lineData: [
        [116, 39],
        [117.0005, 39]
      ]
    }
  },

  mounted() {
    this.initMap();
    this.timer()
  },
  destroyed() {
    clearInterval(this.timer())
  },
  methods: {
    timer() {
      return setInterval(() => {
        this.status = !this.status;
        this.showLine(this.status);
      }, 200)
    },

    showLine(x) {
      this.lineSource.clear(); // 清除上一次绘制的线
      let lineFeature = new Feature({
        geometry: new LineString(this.lineData)
      });
      lineFeature.setStyle(this.featureStyle(x));
      this.lineSource.addFeature(lineFeature);
    },

    featureStyle(x) {
      let style = new Style({
        fill: new Fill({
          color: '#00f'
        }),
        stroke: new Stroke({
          width: 10,
          color: x? '#0f0' : '#f00', // 设置颜色
          lineDash: x? [30, 20] : [20, 30], // 设置虚线
          lineDashOffset: x? 20: 10 // 设置虚线偏移量
        }),
        image: new CircleStyle({
          radius: 10,
          fill: new Fill({
            color: '#ff0000'
          })
        })
      })
      return style;
    },
    initMap() {
      let raster = new Tile({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
        })
      });

      let vector = new VectorLayer({
        source: this.lineSource, // 矢量数据源
      })

      this.map = new Map({
        target: this.$refs.map,
        layers: [raster, vector],
        view: new View({
          center: [113.1206, 23.034996],
          zoom: 10,
          projection: 'EPSG:4326'
        })
      })
      console.log(this.map.getView().getCenter());
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>
